import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers["X-Token"] = getToken();
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 业务逻辑处理
    if (res.code !== 200) {
      Message({
        message: res.message || "操作失败",
        type: "error",
        duration: 5 * 1000,
      });

      // 特殊状态码处理
      if ([401, 508, 512, 514].includes(res.code)) {
        handleUnauthorized();
      }
      return Promise.reject(new Error(res.message || "Error"));
    }
    return res;
  },
  (error) => {
    // HTTP状态码错误处理
    if (error.response) {
      const { status, data } = error.response;

      // 处理401未授权
      if (status === 401) {
        // 如果有后端返回的错误信息，优先显示
        if (data && data.message) {
          Message({
            message: data.message,
            type: "error",
            duration: 5 * 1000,
          });
        } else {
          Message({
            message: "登录已过期，请重新登录",
            type: "error",
            duration: 5 * 1000,
          });
          handleUnauthorized();
        }
        
        return Promise.reject(error);
      }

      // 其他HTTP错误
      Message({
        message: data?.message || `请求错误: ${status}`,
        type: "error",
        duration: 5 * 1000,
      });
    } else {
      // 网络错误等
      Message({
        message: error.message || "网络错误",
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);

// 处理未授权情况
function handleUnauthorized() {
  MessageBox.confirm("登录状态已过期，请重新登录", "确认退出", {
    confirmButtonText: "重新登录",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    store.dispatch("user/resetToken").then(() => {
      location.reload();
    });
  });
}

export default service;
